package com.watson.activity;

import static com.watson.fragment.HomeFragment.U_DEPOT_NAME;

import android.app.Dialog;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.watson.Base2Activity;
import com.watson.MyApp;
import com.watson.R;
import com.watson.adapter.KuwkAdapter;
import com.watson.adapter.KuwrAdapter;
import com.watson.adapter.TaskAdapter;
import com.watson.bean.JsonRootBean;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.DialogUitl;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KuwActivity extends Base2Activity {
    private TextView tvTitle, tv_kw_name, tv_kw_id, tv_kw_num, tvJuku, tvRuku;
    private AppCompatButton btnClaim, btnBack;
    private ImageView img_kw_add;
    private XRecyclerView recyclerData;
    private TextView tvJiazai, tvRight;
    private RecyclerView recyclerKu;
    private KuwkAdapter kuwkAdapter;
    private List<Map> kuData;
    private String Repositoryno = "";
    private KuwrAdapter kuwrAdapter;
    private ArrayList<String> motoridlist;
    private MediaPlayer mediaPlayer;
    private Map dataMap;
    private int maxqty = 0;
    private int qty = 0;
    private String R_Auth_Code = "";
    private List<Map> kuData2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kuw);
        statusbar4();
        dataMap = new HashMap();
        kuData = new ArrayList<>();
        kuData2 = new ArrayList<>();
        motoridlist = new ArrayList<>();
        Repositoryno = getIntent().getStringExtra("no");
        LogUtils.e("TAG", "--------->" + Repositoryno);
        Repositoryno = Repositoryno.replace("K:", "");
        R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
        initView();
        initClick();
        get_WMS_WarehouseEntry_ScanCodeRecords();
        MyApp.setOnImportListener(new MyApp.OnImportListener() {
            @Override
            public void showToastMessage(String message) {
                LogUtils.e("TAG", "message=========>" + message);
                if (!StringUtils.isEmpty(message) && R_Auth_Code.contains("ConfirmWarehousing")) {
                    if (maxqty > (kuData.size() + motoridlist.size()) || maxqty == 0) {
                        if (!motoridlist.toString().contains(message) && !kuData.toString().contains(message)) {
                            ArrayList<Map> numberRuleList = new ArrayList<>();
                            numberRuleList = (ArrayList<Map>) JSON.parseArray(SPUtils.get(mContext, "numberRuleList", "") + "", Map.class);
                            LogUtils.e("TAG", "numberRuleList:" + numberRuleList.toString());
                            if (numberRuleList.size() > 0) {
                                boolean isData = false;
                                for (int i = 0; i < numberRuleList.size(); i++) {
                                    int EngineCodeLenth = Integer.valueOf(numberRuleList.get(i).get("EngineCodeLenth") + "");
                                    if (EngineCodeLenth == message.length()) {
                                        isData = true;
                                    }
                                }

                                if (isData) {
                                    motoridlist.add(message);
                                    kuwrAdapter.setData(motoridlist);
                                    setListView();
                                    ts_cg();
                                } else {
                                    tiDialog("识别码有误,请检查");
                                    ts_cw();
                                }
                            } else {
                                tiDialog("未检测到匹配规则,请重新登录");
                                ts_cw();
                            }
                        } else {
                            tiDialog("该流水号已存在，请核查！");
                            ts_cw();
                        }
                    } else {
                        ts_cw();
                        tiDialog("以达到库位数量，请核查！");
                    }
                }
            }
        });
    }

    private int page = 1;

    private void get_WMS_WarehouseEntry_ScanCodeRecords() {
        HttpClient.getInstance().getData(CommonHttpConsts.get_WMS_WarehouseEntry_ScanCodeRecords, "get_WMS_WarehouseEntry_ScanCodeRecords").headers("token", SPUtils.get(mContext, "token", "") + "").params("Repositoryno", Repositoryno + "")//单号
                .params("whid", U_DEPOT_NAME)//单据归属
//                .params("page", page)
                .execute(new HttpCallbackData() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            dataMap = JSON.parseObject(info, Map.class);
                            LogUtils.e("TAG", "dataMap:" + dataMap.toString());
                            if (!dataMap.isEmpty()) {
                                String codelistStr = dataMap.get("motorids") + "";
                                if (codelistStr.length() > 10) {
                                    kuData = (ArrayList<Map>) JSON.parseArray(codelistStr, Map.class);
                                    if (kuData.size() > 30) {
                                        kuData2 = new ArrayList<>();
                                        kuData2.addAll(kuData.subList(0, 30));
                                    } else {
                                        kuData2 = new ArrayList<>();
                                        kuData2.addAll(kuData);
                                    }
                                    kuwkAdapter.setData(kuData2);
                                }
                                maxqty = Integer.valueOf((StringUtils.isEmpty(dataMap.get("maxqty") + "") ? "0" : dataMap.get("maxqty") + ""));
                                qty = Integer.valueOf((StringUtils.isEmpty(dataMap.get("qty") + "") ? "0" : dataMap.get("qty") + ""));
                                setView();
                                setListView();
                            }
                        } else {
                            ToastUtil.show(msg);
                            finish();
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }

//                    @Override
//                    public void onFinish() {
//                        super.onFinish();
//                        recyclerData.refreshComplete();
//                    }
                });
    }

    private void setView() {
        tv_kw_id.setText(dataMap.get("no") + "");
        tv_kw_name.setText(dataMap.get("name") + "");
        tv_kw_num.setText("数量：" + dataMap.get("qty") + ((maxqty == 0) ? "" : "/" + maxqty));
        if (maxqty == (motoridlist.size() + kuData.size()) && maxqty != 0) {
            tv_kw_num.setVisibility(View.GONE);
        } else {
            tv_kw_num.setVisibility(View.VISIBLE);
        }
    }

    private void setListView() {
        if (kuData.size() > 0) {
            recyclerData.setVisibility(View.VISIBLE);
            tvRuku.setVisibility(View.VISIBLE);
        } else {
            tvRuku.setVisibility(View.GONE);
            recyclerData.setVisibility(View.GONE);
        }

        if (motoridlist.size() > 0) {
            recyclerKu.setVisibility(View.VISIBLE);
            tvJuku.setVisibility(View.VISIBLE);
        } else {
            tvJuku.setVisibility(View.GONE);
            recyclerKu.setVisibility(View.GONE);
        }

        if (!motoridlist.isEmpty() || qty != kuData.size()) {
            if (R_Auth_Code.contains("ConfirmWarehousing")) {
                tvRight.setVisibility(View.VISIBLE);
            }
        }

        if (maxqty == (motoridlist.size() + kuData.size()) && maxqty != 0) {
            tv_kw_num.setVisibility(View.GONE);
        } else {
            tv_kw_num.setVisibility(View.VISIBLE);
        }
        tv_kw_num.setText("数量：" + (motoridlist.size() + kuData.size()) + ((maxqty == 0) ? "" : "/" + maxqty));
    }

    private void initClick() {
        findViewById(R.id.imgBack).setOnClickListener(v -> {
            if (!motoridlist.isEmpty() || qty != kuData.size()) {
                exitDialog(4, 0, "");
            } else {
                finish();
            }
        });

        btnBack.setOnClickListener(v -> {
            SPUtils.remove(mContext, "ck_" + Repositoryno);
            finish();
        });
        tvRight.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (R_Auth_Code.contains("ConfirmWarehousing")) {
                if (maxqty >= (kuData.size() + motoridlist.size()) || maxqty == 0) {
                    exitDialog(3, 0, "");
                } else {
                    ToastUtil.show("扫码数据数量超过库位量，请检查！");
                }
            } else {
                tiDialog("您无入库权限，请联系管理员！");
            }
        });
    }

    private AlertDialog tiDialogs;

    public void tiDialog(String text) {
        if (tiDialogs != null) {
            tiDialogs.dismiss();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_ti, null);
        TextView tvSave = v.findViewById(R.id.tvSave);
        TextView tvName = v.findViewById(R.id.tvNames);
        tiDialogs = builder.create();
        tiDialogs.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!tiDialogs.isShowing()) {//此时提示框未显示
            tiDialogs.show();
        }
        tiDialogs.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        tiDialogs.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        tvName.setText(text);
        //自定义的东西
        tiDialogs.getWindow().setContentView(v);
        tvSave.setOnClickListener(view -> tiDialogs.dismiss());
    }

    private void initView() {
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("库位详情");
        tvRight = findViewById(R.id.tvRight);
        tvRight.setText("提交");
        tvRight.setTextColor(mContext.getResources().getColor(R.color.white));
        tvJiazai = findViewById(R.id.tvJiazai);
        recyclerData = findViewById(R.id.recyclerData);
        recyclerData.setPullRefreshEnabled(false);
        recyclerData.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerData.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        recyclerData.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
        kuwkAdapter = new KuwkAdapter(mContext, kuData);
        recyclerData.setAdapter(kuwkAdapter);
        kuwkAdapter.setItemClickListener(new KuwkAdapter.ItemClickListener() {
            @Override
            public void onClick(int position, Map mList) {
                if (R_Auth_Code.contains("DelInWarehouse")) {
                    exitDialog(1, position, "");
                } else {
                    tiDialog("您无该删除权限，请联系管理员！");
                }
            }
        });
        recyclerKu = findViewById(R.id.recyclerKu);
        recyclerKu.setLayoutManager(new LinearLayoutManager(mContext));
        kuwrAdapter = new KuwrAdapter(mContext, motoridlist);
        recyclerKu.setAdapter(kuwrAdapter);
        kuwrAdapter.setItemClickListener(new KuwrAdapter.ItemClickListener() {
            @Override
            public void onClick(int position, String mList) {
                if (R_Auth_Code.contains("DelNotInWarehouse")) {
                    exitDialog(2, 0, mList);
                } else {
                    tiDialog("您无该删除权限，请联系管理员！");
                }
            }
        });
        tvJuku = findViewById(R.id.tvJuku);
        tvRuku = findViewById(R.id.tvRuku);
        tv_kw_name = findViewById(R.id.tv_kw_name);
        tv_kw_id = findViewById(R.id.tv_kw_id);
        tv_kw_num = findViewById(R.id.tv_kw_num);
        img_kw_add = findViewById(R.id.img_kw_add);
        btnBack = findViewById(R.id.btnBack);
        btnClaim = findViewById(R.id.btnClaim);
        img_kw_add.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (R_Auth_Code.contains("ConfirmWarehousing")) {
                editDialog();
            }
        });
        String cdNo = SPUtils.get(mContext, "ck_" + Repositoryno, "") + "";
        LogUtils.e("TAG", "cdNo--->:" + cdNo);
        if (!StringUtils.isEmpty(cdNo)) {
            motoridlist = JSON.parseObject(SPUtils.get(mContext, "ck_" + Repositoryno, "") + "", ArrayList.class);
            kuwrAdapter.setData(motoridlist);
            LogUtils.e("TAG", "motoridlist:" + motoridlist.toString());
        }
        btnClaim.setVisibility(View.GONE);
        btnBack.setVisibility(View.GONE);

        //recyclerData.setNestedScrollingEnabled(false);
        recyclerData.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                get_WMS_WarehouseEntry_ScanCodeRecords();
            }

            @Override
            public void onLoadMore() {
                page++;
                if (kuData.size() > page * 30) {
                    kuData2.addAll(kuData.subList(kuData2.size(), page * 30));
                } else {
                    kuData2 = new ArrayList<>();
                    kuData2.addAll(kuData);
                }
                kuwkAdapter.setData(kuData2);
                recyclerData.refreshComplete();
//                get_WMS_WarehouseEntry_ScanCodeRecords();
            }
        });
        recyclerData.refreshComplete();
        if (R_Auth_Code.contains("ConfirmWarehousing")) {
            img_kw_add.setVisibility(View.VISIBLE);
        } else {
            img_kw_add.setVisibility(View.GONE);
        }

        tvJiazai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtils.isBaseClick()) {
                    return;
                }
                page++;
                get_WMS_WarehouseEntry_ScanCodeRecords();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!motoridlist.isEmpty() || qty != kuData.size()) {
                exitDialog(4, 0, "");
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exitDialog(int type, int data, String motorid) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvName = v.findViewById(R.id.tvName);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        tvDelete.setText("取消");
        tvSave.setText("确认");
        if (type == 1) {
            tvName.setText("确认删除已入库产品吗？");
        }
        if (type == 2) {
            tvName.setText("确认删除该产品吗");
        }
        if (type == 3) {
            tvName.setText("确认提交数据吗");
        }
        if (type == 4) {
            tvDelete.setText("否");
            tvSave.setText("是");
            tvName.setText("库位产品存在变动，是否取消");
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());

        tvSave.setOnClickListener(view -> {
            if (type == 1) {
//                delete(data);
                kuData.remove(data);
                kuData2.remove(data);
                kuwkAdapter.setData(kuData);
                setListView();
            }
            if (type == 2) {
                motoridlist.remove(motorid);
                kuwrAdapter.setData(motoridlist);
                setListView();
            }
            if (type == 3) {
                update_WMS_WarehouseEntry_ScanCodeRecord();
            }
            if (type == 4) {
                finish();
            }
            dialog.dismiss();
        });
    }

    private void update_WMS_WarehouseEntry_ScanCodeRecord() {
        ArrayList<Map> prolists = new ArrayList<>();
        if (motoridlist.size() > 0) {
            for (int i = 0; i < motoridlist.size(); i++) {
                Map data = new HashMap();
                data.put("motorid", motoridlist.get(i));
                prolists.add(data);
            }
        }
        if (kuData.size() > 0) {
            for (int i = 0; i < kuData.size(); i++) {
                Map data = new HashMap();
                data.put("motorid", kuData.get(i).get("motorid"));
                prolists.add(data);
            }
        }

        Gson gson = new Gson();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scanner_in", SPUtils.get(mContext, "U_Name", ""));
        jsonObject.put("scannerid_in", SPUtils.get(mContext, "U_Id", ""));
        jsonObject.put("repositoryid", dataMap.get("id"));
        jsonObject.put("motoridlist", prolists);
        jsonObject.put("whid", U_DEPOT_NAME);//单据归属
        jsonObject.put("isVerification", SPUtils.get(mContext, "isVerification", false));

        String datStr = gson.toJson(jsonObject);
        datStr = datStr.replaceAll("\\\\", "").trim();

        LogUtils.e("TAG", "datStr:" + datStr);
        HttpClient.getInstance().postData(CommonHttpConsts.update_WMS_WarehouseEntry_ScanCodeRecord, "update_WMS_WarehouseEntry_ScanCodeRecord").headers("token", SPUtils.get(mContext, "token", "") + "").upJson(datStr).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 1001) {
                    ToastUtil.show(msg);
                    ts_cg();
                    motoridlist.clear();
                    SPUtils.remove(mContext, "ck_" + Repositoryno);

                    Intent data = new Intent();
                    data.putExtra("name", true);
                    setResult(RESULT_OK, data);
                    finish();
                } else if (code == 1002) {
                    ts_cw();
                    if (!StringUtils.isEmpty(info)) {
                        exitDialog(msg, info);
                    } else {
                        ToastUtil.show(msg);
                    }
                } else {
                    ToastUtil.show(msg);
                    ts_cw();
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    public void ts_cg() {
        KuwActivity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cg);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    public void ts_cw() {
        KuwActivity.this.runOnUiThread(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            mediaPlayer = MediaPlayer.create(mContext, R.raw.ts_cw);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.start();
        });
    }

    public void editDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_edit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        EditText content = v.findViewById(R.id.content);
        TextView tvSave = v.findViewById(R.id.tvSave);
        LinearLayout lyMima = v.findViewById(R.id.lyMima);
        TextView tvName = v.findViewById(R.id.tvName);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        lyMima.setVisibility(View.GONE);
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());
        tvName.setText("手动输入流水号");

        tvSave.setOnClickListener(view -> {
            String contentStr = content.getText().toString().trim();
            if (StringUtils.isEmpty(contentStr)) {
                ToastUtil.show("请输入流水号");
                return;
            }
            if (contentStr.length() != 19 && contentStr.length() != 20) {
                ToastUtil.show("识别码长度有误！");
                return;
            }
            if (maxqty >= (kuData.size() + motoridlist.size()) || maxqty == 0) {
                if (!motoridlist.contains(contentStr) && !kuData.contains(contentStr)) {
                    motoridlist.add(contentStr);
                    kuwrAdapter.setData(motoridlist);
                    setListView();
                    ToastUtil.show("添加成功");
                    dialog.dismiss();
                } else {
                    ToastUtil.show("已存在该流水号");
                    ts_cw();
                }
            } else {
                ts_cw();
                tiDialog("以达到库位数量，请核查！");
            }
        });
    }

    public void exitDialog(String title, String context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit2, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvContext = v.findViewById(R.id.tvContext);
        TextView tvName = v.findViewById(R.id.tvName);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        tvContext.setMovementMethod(new ScrollingMovementMethod());
        tvName.setText(title);
        String con = context.replace("[", "");
        con = con.replace("]", "");
        con = con.replace(",", "\n");
        tvContext.setText(con);
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());

        tvSave.setOnClickListener(view -> {
            dialog.dismiss();
        });
    }
}
